package studiodiva.portfolio.client.lib.view;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.HeadElement;
import com.google.gwt.dom.client.ScriptElement;

import static studiodiva.portfolio.client.lib.lang.Lang.is;
import static studiodiva.portfolio.client.lib.lang.Lang.no;

public class JsInject {

  private static HeadElement head;

  public static void inject(String value) {
    appendScriptElement().setText(value);
  }

  public static ScriptElement injectSrc(String value) {
    ScriptElement element = appendScriptElement();
    element.setSrc(value);
    return element;
  }

  private static ScriptElement appendScriptElement() {
    return getHead().appendChild(Document.get().createScriptElement());
  }

  private static HeadElement getHead() {
    if (no(head)) {
      Element element = Document.get().getElementsByTagName("HEAD").getItem(0);
      assert is(element) : "HTML Head element required";
      head = HeadElement.as(element);
    }
    return head;
  }

}
